library(tidyverse)
library(fixest)
library(broom)
library(tidymodels)
library(lubridate)
library(stargazer)
library(modelsummary)
library(xtable)
library(sqldf)
library(marginaleffects)
library(here)
library(ggridges)

#Loading Data and Renaming Variables
dat <- read.csv("Hungary_Dat_2.csv")

#renaming codebook below
# dat <- Hungary_Dat %>% 
#   select(caseid, weight, ageGroup, birthyear,
#          gender, region = "GeoPC_Region1_hu", counties = "GeoPC_Region2_hu_manual", education = "education_HU",
#          "education_finished_age" = education_age_EU_local, "employment" = empl_stat_EU, "Household_income" = gross_household_HU,
#          industry = "work_industry_short_EU", party_close, most_liked_party, ideology = "ideo10",
#          democracy_satisfaction = "democ_sat",
#          democracy_change = "democ_change", dempreferable = "dempreferable", strongleader,
#          accountability, rol_support, aware_ecj = "ecjaware",
#          likely_winner, confidence_cc = "confidence_1", 
#          aware_cc = "ccaware", "horizontal_judicial_power_cc" = judicial_power1,
#          "vertical_judicial_power_cc" = judicial_power2,
#          courts_should_be_independent = "independent1",
#          gov_influence_courts_rulings = "independent2", gov_influence_courts = "independent3",
#          confidence_eu = "confidence_5", confidence_gov = "confidence_6",
#          confidence_ecj = "confidence_7", "horizontal_judicial_power_ecj" = ecj_judicial_power1,
#          "vertical_judicial_power_ecj" = ecj_judicial_power2, ecj_final_say_democracy = "ecj_democracy", 
#          ecj_decide_democracy = "ecj_decide", confidence_ecthr = "confidence_8",
#          "horizontal_judicial_power_ecthr" = ecthr_judicial_power1, "vertical_judicial_power_ecthr" = ecthr_judicial_power2,
#          confidence_judciary = "confidence_9", intl_orgs, identity_HU)

####Rescaling all variables between 0 and 1####
dat <- dat %>%
  mutate_at(vars(starts_with("vertical")), ~ ifelse(. == 8, NA, (max(., na.rm = T) - .) / (max(.,na.rm = T) - min(.,na.rm = T)))) %>% #### closer to 1 means more vertical power, 8 = skipped
  mutate_at(vars(starts_with("horizontal")), ~ ifelse(. == 8, NA,(. - min(., na.rm =T)) / (max(., na.rm = T) - min(., na.rm = T)))) %>% #### closer to 1 means more horizontal power, 8 = skipped
  mutate_at(vars(starts_with("confidence")), ~ replace(., . == 4, NA)) %>% ####closer to 1 means higher confidence, turning 4's into NAs because that means no opinion
  mutate_at(vars(starts_with("confidence")), ~ (max(., na.rm = TRUE) - .) / (max(., na.rm = TRUE) - min(., na.rm = TRUE))) %>%
  mutate_at(vars(starts_with("courts_should")), ~ (max(.) - .) / (max(.) - min(.))) %>% #### closer to 1 means courts should be more independent from government
  mutate_at(vars(starts_with("gov_influence")), ~ (max(.) - .) / (max(.) - min(.))) %>% #### closer to 1 means more influence
  mutate_at(vars(starts_with("democracy")), ~ (max(.) - .) / (max(.) - min(.))) %>% #### closer to 1 means democracy getting better/ very satisfied/preferable
  mutate_at(vars(starts_with("likely_winner")), ~ ifelse(. == 8, NA, abs(. - 2))) %>% ####1 means fidesz, 8 skipped the question
  mutate_at(vars(starts_with("most_liked_party")), ~ ifelse(. > 2, NA, abs(. - 2))) %>% ####1 means fidesz, 8 skipped the question, 3 did not vote
  mutate_at(vars(starts_with("ideology")), ~ (. - min(.)) / (max(.) - min(.))) %>% #### closer to 1 means more right wing
  mutate_at(vars(starts_with("ecj_final")), ~ (max(.) - .) / (max(.) - min(.))) %>% #### closer to 1 means SHOULD have final say
  mutate_at(vars(starts_with("aware_ecj")), ~ (max(.) - .) / (max(.) - min(.))) %>% #### closer to 1 means more awareness
  mutate_at(vars(starts_with("ecj_decide")), ~ (. - min(.)) / (max(.) - min(.))) %>% #### closer to 1 means SHOULD decide
  mutate_at(vars(starts_with("strongleader")), ~ ifelse(. == 8, NA, . - 1)) %>% #### closer to 1 means more democracy, 8 = skipped
  mutate_at(vars(starts_with("accountability")), ~ ifelse(. == 8, NA, . - 1)) %>% #### closer to 1 means more accountability, 8 = skipped
  mutate_at(vars(starts_with("rol_support")), ~ ifelse(. == 8, NA, . - 1)) %>% #### closer to 1 means more Rule of Law support, 8 = skipped
  mutate_at(vars(starts_with("dempreferable")), ~ ifelse(. == 8, NA, (max(., na.rm = T) - .) / (max(.,na.rm = T) - min(.,na.rm = T)))) %>%
  mutate_at(vars(starts_with("education")), ~ ifelse(. > 7, 1, 0)) %>%
  mutate_at(vars(starts_with("ageGroup")), ~ (. - min(.)) / (max(.) - min(.))) %>% #1 = 18-29, 2 = 30-44, 3 = 45-64, 4 = 65+
  mutate_at(vars(starts_with("identity_HU")), ~ ifelse(. == 1, 1, 0)) %>% # 1 = hungarian only
  mutate_at(vars(starts_with("gender")), ~ ifelse(. == 2, 1, 0)) #1 = female
  
####Creating Democratic Values variable####
dat$dem_values <- (dat$dempreferable + dat$accountability + dat$strongleader + dat$rol_support)/4

####Regression Models (No interaction) (Table A1)####
dat$opposition <- ifelse(dat$most_liked_party == 0,1,0) #making opposition 1 and fidesz 0 

dem_values_1 <- feols(ecj_final_say_democracy~dem_values,
                      data = dat, vcov = "hetero")
dem_values_bivariate <- tidy(dem_values_1) %>% filter(term == "dem_values") %>% mutate(iv = "Democratic Values", model = "Bivariate" )

dem_values_2 <- feols(ecj_final_say_democracy~ dem_values + confidence_ecj + aware_ecj + ideology + identity_HU + 
                        democracy_satisfaction + gender + ageGroup + education, 
                      data = dat, vcov = "hetero")
dem_values_controls <- tidy(dem_values_2) %>% filter(term == "dem_values") %>% mutate(iv = "Democratic Values", model = "Controls" )

dem_preferable_1 <- feols(ecj_final_say_democracy~dempreferable,
                data = dat, vcov = "hetero")
dem_preferable_bivariate <- tidy(dem_preferable_1) %>% filter(term == "dempreferable") %>% mutate(iv = "Democracy Preferable", model = "Bivariate" )


dem_preferable_2 <- feols(ecj_final_say_democracy~ dempreferable + confidence_ecj + aware_ecj + ideology + identity_HU + 
                        democracy_satisfaction + gender + ageGroup + education, 
                      data = dat, vcov = "hetero")
dem_preferable_controls <- tidy(dem_preferable_2) %>% filter(term == "dempreferable") %>% mutate(iv = "Democracy Preferable", model = "Controls" )

accountability_1 <- feols(ecj_final_say_democracy~accountability,
                data = dat, vcov = "hetero")
accountability_bivariate <- tidy(accountability_1) %>% filter(term == "accountability") %>% mutate(iv = "Accountability", model = "Bivariate" )


accountability_2 <- feols(ecj_final_say_democracy~ accountability + confidence_ecj + aware_ecj + ideology + identity_HU + 
                            democracy_satisfaction + gender + ageGroup + education, 
                          data = dat, vcov = "hetero")
accountability_controls <- tidy(accountability_2) %>% filter(term == "accountability") %>% mutate(iv = "Accountability", model = "Controls" )

strong_leader_1 <- feols(ecj_final_say_democracy~strongleader,
                              data = dat, vcov = "hetero")
strong_leader_bivariate <- tidy(strong_leader_1) %>% filter(term == "strongleader") %>% mutate(iv = "Strong Leader", model = "Bivariate" )


strong_leader_2 <- feols(ecj_final_say_democracy~ strongleader + confidence_ecj + aware_ecj + ideology + identity_HU + 
                                democracy_satisfaction + gender + ageGroup + education, 
                              data = dat, vcov = "hetero")
strong_leader_controls <- tidy(strong_leader_2) %>% filter(term == "strongleader") %>% mutate(iv = "Strong Leader", model = "Controls" )

rol_support_1 <- feols(ecj_final_say_democracy~rol_support,
                         data = dat, vcov = "hetero")
rol_support_bivariate <- tidy(rol_support_1) %>% filter(term == "rol_support") %>% mutate(iv = "Rule of Law Support", model = "Bivariate" )


rol_support_2 <- feols(ecj_final_say_democracy~ rol_support + confidence_ecj + aware_ecj + ideology + identity_HU + 
                           democracy_satisfaction + gender + ageGroup + education, 
                         data = dat, vcov = "hetero")
rol_support_controls <- tidy(rol_support_2) %>% filter(term == "rol_support") %>% mutate(iv = "Rule of Law Support", model = "Controls" )

opposition_1 <- feols(ecj_final_say_democracy~opposition,
                       data = dat, vcov = "hetero")
opposition_bivariate <- tidy(opposition_1) %>% filter(term == "opposition") %>% mutate(iv = "United Opposition Supporter", model = "Bivariate" )


opposition_2 <- feols(ecj_final_say_democracy~ opposition + confidence_ecj + aware_ecj + ideology + identity_HU + 
                         democracy_satisfaction + gender + ageGroup + education, 
                       data = dat, vcov = "hetero")
opposition_controls <- tidy(opposition_2) %>% filter(term == "opposition") %>% mutate(iv = "United Opposition Supporter", model = "Controls" )

####Creating Plot for non-interaction models (Figure 3)####
non_interaction <- rbind(accountability_bivariate,accountability_controls,dem_preferable_bivariate,
                             dem_preferable_controls,rol_support_bivariate,rol_support_controls, strong_leader_bivariate,
                             strong_leader_controls,dem_values_bivariate,dem_values_controls,opposition_bivariate,opposition_controls) %>%
  mutate(iv = fct_relevel(iv, "United Opposition Supporter","Democratic Values",
                                "Accountability", "Rule of Law Support", "Democracy Preferable"),
         model = fct_relevel(model, "Controls","Bivariate"))
 

interval <- qnorm(.975) #95% confidence intervals
dodge <- .5 # for consistency between layers
cbbPalette <- c("#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7") #colorblind friendly palette
non_interaction_plot <- ggplot(non_interaction, aes(x = factor(iv), y = estimate, color = model, shape = model, group = model)) +
  geom_point(size=2,
             position = position_dodge(width = dodge)) +
  geom_errorbar(aes(ymin = estimate-std.error*interval, ymax = estimate+std.error*interval), width = 0.1,
                position = position_dodge(width = dodge)) +
  scale_colour_manual(values=cbbPalette) + geom_hline(yintercept = 0, linetype = "dashed") +
  theme_classic() + coord_flip() + ylab("Estimate") +  
  theme(legend.position = "bottom", legend.title = element_blank(), axis.title.y = element_blank(),
       panel.grid.minor = element_blank())

####Regression Models (with interaction) (Table A2)####
interaction_dem_values_1 <- feols(ecj_final_say_democracy~dem_values*opposition,
                      data = dat, vcov = "hetero")
interaction_dem_values_bivariate <-  avg_slopes(interaction_dem_values_1, by= "dem_values", variables = "opposition") %>%
  mutate(iv = "Democratic Values", model = "Bivariate") %>% rename(value ="dem_values")

interaction_dem_values_2 <- feols(ecj_final_say_democracy~ dem_values*opposition + confidence_ecj + aware_ecj + ideology + identity_HU + 
                        democracy_satisfaction + gender + ageGroup + education, 
                      data = dat, vcov = "hetero")
interaction_dem_values_controls <-  avg_slopes(interaction_dem_values_2, by= "dem_values", variables = "opposition") %>%
  mutate(iv = "Democratic Values", model = "Controls") %>% rename(value ="dem_values")


interaction_dem_preferable_1 <- feols(ecj_final_say_democracy~dempreferable*opposition,
                          data = dat, vcov = "hetero")
interaction_dem_preferable_bivariate <-  slopes(interaction_dem_preferable_1, by= "dempreferable", variables = "opposition") %>%
  mutate(iv = "Democracy Preferable", model = "Bivariate") %>% rename(value ="dempreferable")

interaction_dem_preferable_2 <- feols(ecj_final_say_democracy~ dempreferable*opposition + confidence_ecj + aware_ecj + ideology + identity_HU + 
                            democracy_satisfaction + gender + ageGroup + education, 
                          data = dat, vcov = "hetero")
interaction_dem_preferable_controls <-  avg_slopes(interaction_dem_preferable_2, by= "dempreferable", variables = "opposition") %>%
  mutate(iv = "Democracy Preferable", model = "Controls") %>% rename(value ="dempreferable")

interaction_accountability_1 <- feols(ecj_final_say_democracy~accountability*opposition,
                          data = dat, vcov = "hetero")
interaction_accountability_bivariate <-  avg_slopes(interaction_accountability_1, by= "accountability", variables = "opposition") %>%
  mutate(iv = "Accountability", model = "Bivariate") %>% rename(value ="accountability")

interaction_accountability_2 <- feols(ecj_final_say_democracy~ accountability*opposition + confidence_ecj + aware_ecj + ideology + identity_HU + 
                            democracy_satisfaction + gender + ageGroup + education, 
                          data = dat, vcov = "hetero")
interaction_accountability_controls <-  avg_slopes(interaction_accountability_2, by= "accountability", variables = "opposition") %>%
  mutate(iv = "Accountability", model = "Controls") %>% rename(value ="accountability")

interaction_strong_leader_1 <- feols(ecj_final_say_democracy~strongleader*opposition,
                         data = dat, vcov = "hetero")
interaction_strong_leader_bivariate <-  avg_slopes(interaction_strong_leader_1, by= "strongleader", variables = "opposition") %>%
  mutate(iv = "Strong Leader", model = "Bivariate") %>% rename(value ="strongleader")

interaction_strong_leader_2 <- feols(ecj_final_say_democracy~ strongleader*opposition + confidence_ecj + aware_ecj + ideology + identity_HU + 
                           democracy_satisfaction + gender + ageGroup + education, 
                         data = dat, vcov = "hetero")
interaction_strong_leader_controls <-  avg_slopes(interaction_strong_leader_2, by= "strongleader", variables = "opposition") %>%
  mutate(iv = "Strong Leader", model = "Controls") %>% rename(value ="strongleader")

interaction_rol_support_1 <- feols(ecj_final_say_democracy~rol_support*opposition,
                       data = dat, vcov = "hetero")
interaction_rol_support_bivariate <-  avg_slopes(interaction_rol_support_1, by= "rol_support", variables = "opposition") %>%
  mutate(iv = "Rule of Law Support", model = "Bivariate") %>% rename(value ="rol_support")

interaction_rol_support_2 <- feols(ecj_final_say_democracy~ rol_support*opposition + confidence_ecj + aware_ecj + ideology + identity_HU + 
                         democracy_satisfaction + gender + ageGroup + education, 
                       data = dat, vcov = "hetero")
interaction_rol_support_controls <-  avg_slopes(interaction_rol_support_2, by= "rol_support", variables = "opposition") %>%
  mutate(iv = "Rule of Law Support", model = "Controls") %>% rename(value ="rol_support")

####Robustness check removing democracy satisfaction (Table A3, A4)####
dem_values_3 <- feols(ecj_final_say_democracy~ dem_values + confidence_ecj + aware_ecj + ideology + identity_HU + 
                        gender + ageGroup + education, 
                      data = dat, vcov = "hetero")

dem_preferable_3 <- feols(ecj_final_say_democracy~ dempreferable + confidence_ecj + aware_ecj + ideology + identity_HU + 
                            gender + ageGroup + education, 
                          data = dat, vcov = "hetero")

accountability_3 <- feols(ecj_final_say_democracy~ accountability + confidence_ecj + aware_ecj + ideology + identity_HU + 
                            gender + ageGroup + education, 
                          data = dat, vcov = "hetero")
strong_leader_3 <- feols(ecj_final_say_democracy~ strongleader + confidence_ecj + aware_ecj + ideology + identity_HU + 
                           gender + ageGroup + education, 
                         data = dat, vcov = "hetero")

rol_support_3 <- feols(ecj_final_say_democracy~ rol_support + confidence_ecj + aware_ecj + ideology + identity_HU + 
                         gender + ageGroup + education, 
                       data = dat, vcov = "hetero")

opposition_3 <- feols(ecj_final_say_democracy~ opposition + confidence_ecj + aware_ecj + ideology + identity_HU + 
                        gender + ageGroup + education, 
                      data = dat, vcov = "hetero")

interaction_dem_values_3 <- feols(ecj_final_say_democracy~ dem_values*opposition + confidence_ecj + aware_ecj + ideology + identity_HU + 
                                    gender + ageGroup + education, 
                                  data = dat, vcov = "hetero")

interaction_dem_preferable_3 <- feols(ecj_final_say_democracy~ dempreferable*opposition + confidence_ecj + aware_ecj + ideology + identity_HU + 
                                        gender + ageGroup + education, 
                                      data = dat, vcov = "hetero")

interaction_accountability_3 <- feols(ecj_final_say_democracy~ accountability*opposition + confidence_ecj + aware_ecj + ideology + identity_HU + 
                                        gender + ageGroup + education, 
                                      data = dat, vcov = "hetero")

interaction_strong_leader_3 <- feols(ecj_final_say_democracy~ strongleader*opposition + confidence_ecj + aware_ecj + ideology + identity_HU + 
                                       gender + ageGroup + education, 
                                     data = dat, vcov = "hetero")

interaction_rol_support_3 <- feols(ecj_final_say_democracy~ rol_support*opposition + confidence_ecj + aware_ecj + ideology + identity_HU + 
                                     gender + ageGroup + education, 
                                   data = dat, vcov = "hetero")

####Marginal Effects Plot for Dem value components (Figure 4)###
interaction <- rbind(interaction_accountability_bivariate,interaction_accountability_controls,
                     interaction_dem_preferable_bivariate, interaction_dem_preferable_controls,
                     interaction_rol_support_bivariate,interaction_rol_support_controls, 
                     interaction_strong_leader_bivariate,interaction_strong_leader_controls,
                     interaction_dem_values_bivariate, interaction_dem_values_controls) %>%
  mutate(iv = fct_relevel(iv, "Accountability", "Rule of Law Support", "Democracy Preferable", "Strong Leader"))

interaction_plot <- ggplot(interaction, aes(x = factor(value), y = estimate, color = model, shape = model)) +
  geom_point(size=2,
             position = position_dodge(width = dodge)) + geom_line(linetype = "dashed") +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = 0.1,
                position = position_dodge(width = dodge)) +
  scale_colour_manual(values=cbbPalette) +
  #scale_x_discrete(breaks=seq(0.,1,0.25), limits=c(0.0, 0.0)) +
  facet_wrap(~iv) + ylab("Marginal Effect of United Opposition") +
  geom_hline(yintercept = 0, linetype = "dashed") +
  theme_bw() + 
  theme(legend.position = c(0.85,.25), legend.title = element_blank(), 
        axis.title.x = element_blank(), 
        panel.grid.major = element_blank(), panel.grid.minor = element_blank())

####Regression Tables####

dict = c("opposition" = "United Opposition Supporter", "confidence_ecj" = "CJEU Confidence",
         "aware_ecj" = "CJEU Awareness", "ideology" = "Ideology", "identity_HU" = "National Identity",  
           "democracy_satisfaction" = "Democratic Satisfaction", "gender" = "Gender",
         "ageGroup" = "Age", "education" = "Education"," dempreferable" = "Democracy Preferable",
         "accountability" = "Accountability", "strongleader" = "Strong Leader", "rol_support" = "Rule of Law",
         "ecj_final_say_democracy" = "CJEU Judicial Power", "dem_values" = "Democratic Values")

#Table A1
etable(accountability_1,accountability_2,rol_support_1, rol_support_2,
       dem_preferable_1, dem_preferable_2, strong_leader_1, strong_leader_2,
       dem_values_1, dem_values_2,opposition_1, opposition_2,
       dict = dict, 
       title = "Results for Hypothesis 1 and Hypothesis 2",
       style.tex = style.tex("aer"), 
       fitstat = ~ r2 + n, tex = T,
       digits = "r4",
       notes = "Heteroskedasticity robust standard errors in parentheses.\\ $^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01")

#Table A2
etable(interaction_accountability_1,interaction_accountability_2,
       interaction_rol_support_1, interaction_rol_support_2,
       interaction_dem_preferable_1, interaction_dem_preferable_2, 
       interaction_strong_leader_1, interaction_strong_leader_2,
       interaction_dem_values_1, interaction_dem_values_2,
       dict = dict, 
       title = "Results for Hypothesis 3",
       style.tex = style.tex("aer"), 
       fitstat = ~ r2 + n, tex = T,
       digits = "r4",
       notes = "Heteroskedasticity robust standard errors in parentheses.\\ $^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01")

#Robustness Table A3
etable(accountability_3,rol_support_3,
       dem_preferable_3, strong_leader_3,
       dem_values_3,opposition_3,
       dict = dict, 
       title = "Results for Hypothesis 1 and Hypothesis 2 without Democratic Satisfaction",
       style.tex = style.tex("aer"), 
       fitstat = ~ r2 + n, tex = T,
       digits = "r4",
       notes = "Heteroskedasticity robust standard errors in parentheses.\\ $^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01")

#Robustness Table A4
etable(interaction_accountability_3,
       interaction_rol_support_3,
       interaction_dem_preferable_3, 
       interaction_strong_leader_3,
       interaction_dem_values_3,
       dict = dict, 
       title = "Results for Hypothesis 3 without Democratic Satisfaction",
       style.tex = style.tex("aer"), 
       fitstat = ~ r2 + n, tex = T,
       digits = "r4",
       notes = "Heteroskedasticity robust standard errors in parentheses.\\ $^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01")


####Ridge Plot Figure 1####
cbbPalette <- c("#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7") #colorblind friendly palette

#Creating dataframe for plot
dv_groups <- dat %>% filter(!is.na(most_liked_party)) %>%
  select(most_liked_party, "Strong Leader" = strongleader, 
         Accountability = accountability, 
         "Rule of Law Support" = rol_support, 
         "Democracy Preferable" = dempreferable,
         "Democratic Values Average" = dem_values,
         "CJEU Judicial Power" = ecj_final_say_democracy) %>%
  pivot_longer(!most_liked_party, names_to = "variable", values_to = "outcome") %>% 
  mutate(party = ifelse(most_liked_party == 1, "Fidesz Supporters", "United Opposition Supporters")) %>%
  mutate(variable = fct_relevel(variable, "CJEU Judicial Power","Democratic Values Average",
                                "Accountability", "Rule of Law Support", "Democracy Preferable"))
 
#Creating plot
ggplot(dv_groups, aes(x = outcome, y = variable, fill = factor(party), linetype = factor(party))) +
  geom_density_ridges(scale = 1.5, alpha = 0.4) + 
  scale_y_discrete(expand = c(0, 0)) +     # will generally have to set the `expand` option
  scale_x_continuous(expand = c(0, 0), breaks = c(0,.25,.5,.75,1)) +   # for both axes to remove unneeded padding
  coord_cartesian(clip = "off") + # to avoid clipping of the very top of the top ridgeline
  theme_ridges() + theme(legend.position = "bottom", legend.title = element_blank(), 
                         axis.title.x = element_blank(), axis.title.y = element_blank(), 
                         panel.grid.major = element_blank()) + 
  scale_fill_manual(values = cbbPalette)

####Descriptive plot of all models (Figure 2)####

descriptive <- dv_groups <- dat %>% filter(!is.na(most_liked_party),) %>%
  select(Party = most_liked_party, caseid, "Strong Leader" = strongleader, 
         Accountability = accountability, 
         "Rule of Law Support" = rol_support, 
         "Democracy Preferable" = dempreferable,
         "Democratic Values Average" = dem_values,
         ecj_final_say_democracy) %>%
  pivot_longer(-c(caseid,Party,ecj_final_say_democracy), names_to = "variable", values_to = "outcome") %>% 
  mutate(Party = ifelse(Party == 1, "Fidesz Supporters", "United Opposition Supporters")) %>%
  filter(!is.na(outcome)) %>%
  group_by(Party,variable, outcome) %>%
  summarise(mean = mean(ecj_final_say_democracy, na.rm = TRUE),
            sd = sd(ecj_final_say_democracy, na.rm = TRUE),
            n = n()) %>%
  mutate(se = sd / sqrt(n),
         lower.ci = mean - qt(1 - (0.05 / 2), n - 1) * se,
         upper.ci = mean + qt(1 - (0.05 / 2), n - 1) * se) %>%
  mutate(variable = fct_relevel(variable, "Democratic Values Average",
                                "Accountability", "Rule of Law Support", "Democracy Preferable"))

dodge <- .5 # for consistency between layers
ggplot(descriptive, aes(x = factor(outcome), y = mean, color = Party, shape = Party, group = Party)) +
  geom_point(size=2,
             position = position_dodge(width = dodge)) + geom_line(linetype = "dashed") +
  geom_errorbar(aes(ymin = lower.ci, ymax = upper.ci), width = 0.1,
                position = position_dodge(width = dodge)) +
  scale_colour_manual(values=cbbPalette) +
  #scale_x_discrete(breaks=seq(0.,1,0.25), limits=c(0.0, 0.0)) +
  facet_wrap(~variable) + ylab("CJEU Judicial Power") +
  theme_bw() + 
  theme(legend.position = c(0.85,.25), legend.title = element_blank(), 
        axis.title.x = element_blank(), 
        panel.grid.major = element_blank(), panel.grid.minor = element_blank())

####Descriptive Statistics (Table 1)####

modsum_dat <- dat %>% select(opposition, "CJEU Confidence" = "confidence_ecj" ,
                             "CJEU Awareness"="aware_ecj","Ideology" = "ideology", "National Identity"= "identity_HU",  
                             "Democratic Satisfaction"= "democracy_satisfaction", "Gender"= "gender",
                             "Age"= "ageGroup", "Education"= "education", "Democracy Preferable" = "dempreferable",
                             "Accountability"="accountability", "Strong Leader"="strongleader", "Rule of Law"="rol_support",
                             "CJEU Judicial Power"="ecj_final_say_democracy", "Democratic Values"="dem_values")  
modsum_dat$opposition <- ifelse(modsum_dat$opposition ==1, "United Opposition Supporter", "Fidesz Supporter")
datasummary_balance(~opposition, modsum_dat,
                    fmt = 4, output = 'latex')

#####Other Interactions Plot Robustness (Figure A1)#####

interaction_confidence_2 <- feols(ecj_final_say_democracy~ dem_values*confidence_ecj + opposition + aware_ecj + ideology + identity_HU + 
                                    democracy_satisfaction + gender + ageGroup + education, 
                                  data = dat, vcov = "hetero")
interaction_confidence_controls <-  avg_slopes(interaction_confidence_2, by= "dem_values", variables = "confidence_ecj") %>%
  mutate(iv = "CJEU Confidence", model = "Controls") %>% rename(value ="dem_values")

interaction_identity_2 <- feols(ecj_final_say_democracy~ dem_values*identity_HU + confidence_ecj + opposition + aware_ecj + ideology + 
                                    democracy_satisfaction + gender + ageGroup + education, 
                                  data = dat, vcov = "hetero")
interaction_identity_controls <-  avg_slopes(interaction_identity_2, by= "dem_values", variables = "identity_HU") %>%
  mutate(iv = "National Identity", model = "Controls") %>% rename(value ="dem_values")

interaction_ideology_2 <- feols(ecj_final_say_democracy~ dem_values*ideology + identity_HU + confidence_ecj + opposition + aware_ecj +  
                                  democracy_satisfaction + gender + ageGroup + education, 
                                data = dat, vcov = "hetero")
interaction_ideology_controls <-  avg_slopes(interaction_ideology_2, by= "dem_values", variables = "ideology") %>%
  mutate(iv = "Ideology", model = "Controls") %>% rename(value ="dem_values")

interaction_eu_2 <- feols(ecj_final_say_democracy~ dem_values*confidence_eu + ideology + identity_HU + confidence_ecj + opposition + aware_ecj +  
                                  democracy_satisfaction + gender + ageGroup + education, 
                                data = dat, vcov = "hetero")
interaction_eu_controls <-  avg_slopes(interaction_eu_2, by= "dem_values", variables = "confidence_eu") %>%
  mutate(iv = "EU Confidence", model = "Controls") %>% rename(value ="dem_values")

interaction <- rbind(interaction_accountability_bivariate,interaction_accountability_controls,
                     interaction_dem_preferable_bivariate, interaction_dem_preferable_controls,
                     interaction_rol_support_bivariate,interaction_rol_support_controls, 
                     interaction_strong_leader_bivariate,interaction_strong_leader_controls,
                     interaction_dem_values_bivariate, interaction_dem_values_controls) %>%
  mutate(iv = fct_relevel(iv, "Accountability", "Rule of Law Support", "Democracy Preferable", "Strong Leader"))

####Robustness plot
robustness <- rbind(interaction_confidence_controls, interaction_identity_controls,
                    interaction_eu_controls, interaction_ideology_controls)

ggplot(robustness, aes(x = factor(value), y = estimate)) +
  geom_point(size=2,
             position = position_dodge(width = dodge)) + geom_line(linetype = "dashed") +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = 0.1,
                position = position_dodge(width = dodge)) +
  scale_colour_manual(values=cbbPalette) +
  #scale_x_discrete(breaks=seq(0.,1,0.25), limits=c(0.0, 0.0)) +
  facet_wrap(~iv) + xlab("Democratic Values") + ggtitle("Marginal Effect of other Independent Variables") +
  ylab("Average Marginal Effect on CJEU Judicial Power") +
  geom_hline(yintercept = 0, linetype = "dashed") +
  theme_bw() + 
  theme(legend.position = c(0.85,.25), legend.title = element_blank(), 
        panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        plot.title = element_text(hjust = 0.5))